/**
 * @author Liaorun
 */
public class Islands {

    public static void main(String[] args) {
        int[][] data = {{1, 0, 0, 0, 0, 0, 0, 0, 0}, {1, 1, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 1, 0, 0, 0}, {0, 1, 1, 1, 1, 1, 1, 1, 1},};

        System.out.println(countIsLands(data));
    }

    public static int countIsLands(int[][] m) {
        if (m == null || m[0] == null) {
            return 0;
        }

        int row = m.length;
        int col = m[0].length;
        int res = 0;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (m[i][j] == 1) {
                    res++;
                    infect(m, i, j, row, col);
                }
            }
        }


        return res;
    }

    /**
     * 将上下左右所有的1变成2
     *
     * @param m 源2维数组
     * @param i 横坐标
     * @param j 纵坐标
     * @param row 最大横坐标
     * @param col 最大纵坐标
     */
    private static void infect(int[][] m, int i, int j, int row, int col) {

        // 边界条件判断
        if (i < 0 || i >= row || j < 0 || j >= col || m[i][j] != 1) {
            return;
        }

        // i, j没越界，并且当前位置值是1
        m[i][j] = 2;
        // 感染上下左右相邻的点
        infect(m, i + 1, j, row, col);
        infect(m, i - 1, j, row, col);
        infect(m, i, j + 1, row, col);
        infect(m, i, j - 1, row, col);
    }
}
